import email
from flask import Blueprint, request, jsonify

from exts import db, redis_sever
from models import User

# 声明忘记密码蓝图
bp = Blueprint("forgetpasswd", __name__, url_prefix="/forgetpasswd")

# 执行修改密码操作
@bp.route("/do", methods=["POST", "GET"])
def do_forgetpasswd():
    forgetpasswd_data = request.get_json()
    # forgetpasswd_data = {'email': '123@qq.com', 'password': '123', 'confirm': '123', 'captcha': 'w0nie9'}
    # 预防用户直接通过链接去访问
    if not forgetpasswd_data:
        return "请按系统的步骤, 正常去注册", 400
    # 检测邮箱是否注册过,只有注册过的才能进行修改密码
    email_error = True if len(User.query.filter(User.email == forgetpasswd_data.get("email")).all()) != 0 else False
    if email_error:
        # 先检验redis中是否有验证码，验证码不能为空，为空直接返回验证码错误给前端
        captcha = redis_sever.get(forgetpasswd_data["email"])
        if captcha == forgetpasswd_data["captcha"].lower() and captcha:
            # 验证正确向数据库修改数据
            User.query.filter(User.email == forgetpasswd_data["email"]).update({"password": forgetpasswd_data["password"]})
            db.session.commit()
            return jsonify({"message":{"success":True}})
        else:
            # 验证码错误
            return jsonify({"message": {"captcha_error": True}})
    else:
        return jsonify({"message":{"email_error": not email_error}})
    
    # 检测验证码是否正确
    
    print(forgetpasswd_data)
    return "sunccess"